package com.wave2.shadow.controller;

import java.util.ArrayList;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.beans.factory.annotation.Autowired;
import com.wave2.shadow.exceptions.UserAlreadyExists;
import com.wave2.shadow.model.JoinForm;
import com.wave2.shadow.services.JGARegistrationService;
import com.wave2.shadow.validator.JoinFormValidator;

@Controller("jgacontroller")
@SessionAttributes("JoinForm")
public class JGAController {

	@Autowired
	private JGARegistrationService jgaRegistrationService;

	@Autowired
	private JoinFormValidator joinFormValidator;

	public void setJoinFormValidator(JoinFormValidator joinFormValidator) {
		this.joinFormValidator = joinFormValidator;
	}

	@RequestMapping(value = "add.htm", method = RequestMethod.GET)
	public String showJoinForm(ModelMap model) {
		JoinForm user = new JoinForm();
		model.addAttribute("JoinForm", user);
		return "join";
	}

	@RequestMapping(value = "add.htm", method = RequestMethod.POST)
	public String processForm(@ModelAttribute("JoinForm") JoinForm form, BindingResult result, Map<String, Object> model) {
		String returnView = "login";

		// checks to see if form input values are good.
		joinFormValidator.validate(form, result);
		
		try {
			
			if (result.hasErrors()) {
				returnView = "join";
			} else {

				jgaRegistrationService.createUser(form);
				model.put("email", form.getEmail());
			}
			
		} catch (UserAlreadyExists e) {
			
			// User already existed in DB. Send message to join form.
			ArrayList<String> messages = new ArrayList<String>();
			messages.add("User Already Exists in Database. Please reset password or use a different email address.");
			
			model.put("messages", messages);
			model.put("enteredData", form);
			
			returnView = "join";
		} catch (Exception e) {
			// User already existed in DB. Send message to join form.
			ArrayList<String> messages = new ArrayList<String>();
			messages.add("Fatal Error Occured!<br/>" + e.getMessage());
			
			model.put("messages", messages);
			model.put("enteredData", form);			
			
			e.printStackTrace(System.err);
		}

		return returnView;
	}

}
